package com.task.manage;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class JobManage {

	@Autowired
	private Scheduler scheduler;

	/**
	 * 启动一个调度对象
	 * 
	 * @throws SchedulerException
	 */
	public void start() throws SchedulerException {

		scheduler.start();
	}

	/**
	 * 检查调度是否启动
	 * 
	 * @return
	 * @throws SchedulerException
	 */
	public boolean isStarted() throws SchedulerException {
		return scheduler.isStarted();
	}

	/**
	 * 关闭调度信息
	 * 
	 * @throws SchedulerException
	 */
	public void shutdown() throws SchedulerException {
		scheduler.shutdown();
	}

	/**
	 * @Title: JobManage.java
	 * @Description: 添加任务
	 * @param taskclass
	 * @param jobname
	 * @param jobgroup
	 * @param cronExpression
	 * @return
	 */
	public Date addjob(String taskid, Job taskclass, String jobname, String jobgroup, String cronExpression,
			String begintime, String endtime, String remark) {
		try {

			// 指明job的名称，所在组的名称，以及绑定job类
			JobDetail job = JobBuilder.newJob(taskclass.getClass()).withIdentity(jobname, jobgroup).build();

			job.getJobDataMap().put("taskid", taskid);
			job.getJobDataMap().put("remark", remark);
			// 定义调度触发规则
			// 使用cornTrigger规则 每天10点42分

			Date date = null;
			Date date1 = null;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			try {
				date = sdf.parse(begintime);
				date1 = sdf.parse(endtime);
			} catch (Exception e) {

			}

			Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobname, jobgroup)
					.withSchedule(
							CronScheduleBuilder.cronSchedule(cronExpression).withMisfireHandlingInstructionDoNothing())
					.startAt(date).endAt(date1).build();

			// 把作业和触发器注册到任务调度中
			return scheduler.scheduleJob(job, trigger);
		} catch (SchedulerException e) {
			System.err.println(e.getMessage() + "-" + remark);
			return null;
		}
	}

	public Date addjobforone(String taskid, Job taskclass, String jobname, String jobgroup, String remark) {

		try {
			// 指明job的名称，所在组的名称，以及绑定job类
			JobDetail job = JobBuilder.newJob(taskclass.getClass()).withIdentity(jobname, jobgroup).build();

			job.getJobDataMap().put("taskid", taskid);
			job.getJobDataMap().put("remark", remark);

			SimpleTrigger simpleTrigger = TriggerBuilder.newTrigger().withIdentity(jobname, jobgroup)
					.startAt(new Date())
					.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3).withRepeatCount(0))// 重复执行的次数，因为加入任务的时候马上执行了，所以不需要重复，否则会多一次。
					.build();

			// 把作业和触发器注册到任务调度中
			return scheduler.scheduleJob(job, simpleTrigger);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * 删除相关的job任务
	 * 
	 * @param jobkey
	 * @return
	 * @throws SchedulerException
	 */
	public boolean deleteJob(String jobname, String jobgroup) {
		try {
			for (String groupName : scheduler.getJobGroupNames()) {
				for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {

					String jobName = jobKey.getName();
					String jobGroup = jobKey.getGroup();
					if (jobName.equalsIgnoreCase(jobName) && jobGroup.equalsIgnoreCase(jobgroup)) {
						return scheduler.deleteJob(jobKey);
					}
				}
			}
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		return true;
	}

}
